package com.shch.tools.controller;

import com.alibaba.fastjson.JSON;
import com.maxmind.geoip.Location;
import com.shch.tools.utils.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class IpController {
    /**
     * Ip地址转换
     * @param ip
     * @param request
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String getLocationByIP(@RequestParam("ip") String ip, HttpServletRequest request){
        Location location ;
        if (StringUtils.isEmpty(ip)){
            location = IpUtil.getCityByIp(IpUtil.getIpAddr(request));
        } else {
            if (IpUtil.ipCheck(ip)) {
                location = IpUtil.getCityByIp(ip);
            } else {
                return "您输入的ip："+ip+"不合法,请输入合法的ip地址";
            }
        }
        return JSON.toJSONString(location);
    }
}
